# -*- encoding: utf-8 -*-

"""
@File:      tc_libfastjson_libfastjson_func_004.py
@Time:      2024/04/01 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libfastjson_libfastjson_func_004.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libfastjson libfastjson-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >fjson_test4.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <libfastjson/json.h>

#define NUM_THREADS 5

// 线程要运行的函数
void *thread_function(void *arg) {
    // 创建一个 JSON 对象
    fjson_object *json_obj = fjson_object_new_object();
    fjson_object_object_add(json_obj, "thread_id", fjson_object_new_int((long)arg));
    fjson_object_object_add(json_obj, "message", fjson_object_new_string("Hello from thread"));

    // 将 JSON 对象转换为字符串并复制到一个局部缓冲区中
    const char *json_str_temp = fjson_object_to_json_string(json_obj);
    char *json_str = strdup(json_str_temp); // 使用 strdup 复制字符串
    printf("Thread %ld: %s\\n", (long)arg, json_str);

    // 释放 JSON 对象的内存
    fjson_object_put(json_obj);

    // 解析 JSON 字符串
    fjson_object *parsed_json = fjson_tokener_parse(json_str);
    if (parsed_json == NULL) {
        fprintf(stderr, "Error parsing JSON string in thread %ld\\n", (long)arg);
    } else {
        // 处理解析后的 JSON 对象，这里只是简单地打印出它
        printf("Thread %ld parsed JSON: %s\\n", (long)arg, fjson_object_to_json_string(parsed_json));
        // 释放解析后的 JSON 对象的内存
        fjson_object_put(parsed_json);
    }

    // 释放复制的字符串内存
    free(json_str);

    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];

    // 创建多个线程执行 JSON 操作
    for (long i = 0; i < NUM_THREADS; ++i) {
        if (pthread_create(&threads[i], NULL, thread_function, (void *)i)) {
            fprintf(stderr, "Error creating thread\\n");
            return EXIT_FAILURE;
        }
    }

    // 等待所有线程完成
    for (int i = 0; i < NUM_THREADS; ++i) {
        pthread_join(threads[i], NULL);
    }

    return EXIT_SUCCESS;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o fjson_test4 fjson_test4.c -lfastjson -lpthread")
        code, fjson_result = self.cmd("./fjson_test4")
        self.assertIn('Thread 4 parsed JSON: { "thread_id": 4, "message": "Hello from thread" }', fjson_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf fjson_test4.c fjson_test4")
